<template>
  <div>
    <el-card>
      <CategoryList :disabled="!isShowList"></CategoryList>
    </el-card>

    <el-card v-show="isShowList" style="margin-top: 10px">
      <el-button
        type="primary"
        :icon="Plus"
        @click="addAttr"
        style="margin-bottom: 20px"
        :disabled="!category3Id">
        添加属性
      </el-button>
      <el-table border :data="AttrList">
        <el-table-column type="index" label="序号" width="80"></el-table-column>
        <el-table-column
          prop="attrName"
          label="属性名称"
          width="200"></el-table-column>
        <el-table-column label="属性值列表">
          <template v-slot="{ row }">
            <el-tag v-for="item in row.attrValueList" style="margin-right: 5px">
              {{ item.valueName }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template v-slot="{ row }">
            <el-button
              type="primary"
              :icon="Edit"
              size="small"
              @click="updateAttr(row)"></el-button>

            <el-popconfirm
              :title="`是否删除${row.attrName}?`"
              @confirm="removeAttr(row.id)">
              <template #reference>
                <el-button
                  type="danger"
                  :icon="Delete"
                  size="small"></el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-card v-show="!isShowList" style="margin-top: 10px">
      <span style="margin-right: 20px">属性名</span>
      <el-input
        v-model="Attr.attrName"
        placeholder="请输入属性名"
        style="width: 200px"></el-input>

      <div style="margin: 20px 0">
        <el-button
          type="primary"
          :icon="Plus"
          @click="addAttrVlaue"
          :disabled="!Attr.attrName">
          添加属性值
        </el-button>
        <el-button @click="isShowList = true">取消</el-button>
      </div>
      <el-table :data="Attr.attrValueList">
        <el-table-column
          type="index"
          label="序号"
          width="80px"></el-table-column>
        <el-table-column label="属性值名称">
          <template v-slot="{ row, $index }">
            <el-input
              v-if="row.isInput"
              v-model="row.valueName"
              @blur="toShow(row, $index)"
              ref="InputRef"></el-input>
            <span
              v-else
              @click="toEdit(row)"
              style="display: inline-block; width: 100%">
              {{ row.valueName }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template v-slot="{ row, $index }">
            <el-button
              type="danger"
              :icon="Delete"
              size="small"
              @click="Attr.attrValueList.splice($index, 1)"></el-button>
          </template>
        </el-table-column>
      </el-table>
      <div style="margin: 20px 0">
        <el-button type="primary" @click="saveAttr" :disabled="isSave">
          保存
        </el-button>
        <el-button @click="isShowList = true">取消</el-button>
      </div>
    </el-card>
  </div>
</template>

<script lang="ts">
import { defineComponent } from "vue";
import { ElMessage } from "element-plus";
import { storeToRefs } from "pinia";

export default defineComponent({
  name: "Attr",
});
</script>

<script setup lang="ts">
import { deleteAttrApi, getAttrListApi, saveAttrApi } from "@/api/product/attr";
import type {
  attrListModel,
  attrModel,
  attrValueModel,
} from "@/api/product/model/attrModel";
import { Delete, Plus } from "@element-plus/icons-vue";
import useCategoryStore from "@/stores/category";
import { ref, watch, nextTick, computed } from "vue";
import { useRoute } from "vue-router";

import { Edit } from "@element-plus/icons-vue";

import { cloneDeep } from "lodash";

// 计算保存修改的按钮的禁用条件
const isSave = computed(() => {
  const hasnaem = Attr.value.attrName === "";

  // 当属性值没有长度的时候 或者一个长度 但是属性值为空的
  const hasValue =
    Attr.value.attrValueList.length === 0 ||
    (Attr.value.attrValueList.length === 1 &&
      Attr.value.attrValueList[0]?.valueName === "");

  return hasnaem || hasValue;
});

const CategoryStore = useCategoryStore();

const { category1Id, category3Id, category2Id } = storeToRefs(CategoryStore);
const AttrList = ref<attrListModel>([]);

const getAttrList = async () => {
  AttrList.value = await getAttrListApi(
    CategoryStore.category1Id as number,
    CategoryStore.category2Id as number,
    CategoryStore.category3Id as number
  );
};
// 侦听到3id的改变 渲染下面的列表
watch(
  () => CategoryStore.category3Id,
  async (val) => {
    if (val) {
      getAttrList();
    } else {
      AttrList.value = [];
    }
  }
);

const route = useRoute();
// 路由发送改变 清空三级分类的数据
watch(route, () => {
  CategoryStore.removeList();
});

const isShowList = ref(true);
const initattr = () => ({
  attrName: "",
  attrValueList: [],
  categoryId: 1,
  categoryLevel: 3,
});

// 初始化一个数据
const Attr = ref<attrModel>(initattr());

// 点击新增属性
const addAttr = () => {
  isShowList.value = false;
  Object.assign(Attr.value, initattr());
};

// 点击修改属性
const updateAttr = (row: attrModel) => {
  isShowList.value = false;
  Object.assign(Attr.value, cloneDeep(row));
};

//
const InputRef = ref();

// 显示查看属性值
const toShow = (row: attrValueModel, index: number) => {
  row.isInput = false;
  if (!row.valueName) {
    Attr.value.attrValueList.splice(index, 1);
  }
  const is = Attr.value.attrValueList.some(
    (item) => item !== row && row.valueName === item.valueName
  );
  if (is) {
    ElMessage.warning("属性值不能重复");
    Attr.value.attrValueList.splice(index, 1);
  }
};
// 显示输入框
const toEdit = (row: attrValueModel) => {
  row.isInput = true;
  nextTick(() => {
    (InputRef.value as HTMLInputElement).focus();
  });
};

// 定义一个初始的属性值对象

// 点击添加 属性值
const addAttrVlaue = () => {
  const initValue: attrValueModel = {
    valueName: "", // 属性值名称
    attrId: Attr.value.id as number, // 属性的id
    isInput: true, // 标识显示input
  };
  Attr.value.attrValueList.push(initValue);
  nextTick(() => {
    (InputRef.value as HTMLInputElement).focus();
  });
};

// 点击保存
const saveAttr = async () => {
  Attr.value.attrValueList.forEach((item) => delete item.isInput);
  Attr.value.categoryId = CategoryStore.category3Id as number;

  await saveAttrApi(Attr.value);
  ElMessage.success("保存成功");
  isShowList.value = true;

  getAttrList();
};

// 点击删除属性
const removeAttr = async (id: number) => {
  await deleteAttrApi(id);
  ElMessage.success("删除成功");
  getAttrList();
};
</script>

<style scoped lang="scss"></style>
